﻿using System;
using Validity.Contexts;
using Validity.Localization;
using Validity.Rules;

namespace Validity
{
  public static class EndsWithConstraint
  {
    public static IConditionalValidationContext<TObject, String> EndsWith<TObject>(this IValidationContext<TObject, String> context, String value)
    {
      return context.EndsWith(obj => value);
    }

    public static IConditionalValidationContext<TObject, String> EndsWith<TObject>(this IValidationContext<TObject, String> context, Func<String> valueRetriever)
    {
      Verify.NotNull(valueRetriever);
      return context.EndsWith(obj => valueRetriever.Invoke());
    }

    public static IConditionalValidationContext<TObject, String> EndsWith<TObject>(this IValidationContext<TObject, String> context, Func<TObject, String> valueRetriever)
    {
      Verify.NotNull(valueRetriever);

      context.AddRule(new Rule<TObject, String>(
        (obj, val) => (val ?? String.Empty).EndsWith(valueRetriever.Invoke(obj) ?? String.Empty),
        (obj, val) => String.Format(RuleViolations.EndsWith, valueRetriever.Invoke(obj))
      ));

      return new ConditionalValidationContext<TObject, String>(context);
    }
  }
}
